<template>
  <teleport to="#app">
    <div class="top-bar">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-top"
        mode="horizontal"
        router
        unique-opened
        @select="handleSelect"
      >
        <template
          v-for="(menu, i) of menus"
          :key="menu.title"
        >
          <el-submenu
            v-if="menu.children &&menu.children.length"
            index="2"
          >
            <template #title>
              {{ menu.title }}
            </template>
            <el-menu-item
              v-for="(submenu, j) of menu.children"
              :key="submenu.title"
              :index=" i + '-'+ j"
              :route="submenu.route"
            >
              {{ submenu.title }}
            </el-menu-item>
          </el-submenu>
          <el-menu-item
            :index="'' + i"
            :route="menu.route"
          >
            {{ menu.title }}
          </el-menu-item>
        </template>
      </el-menu>

      <div
        v-if="profile"
        class="profile"
        @click="signout"
      >
        <i class="el-icon-user-solid" />{{ user }}
      </div>
    </div>
  </teleport>
</template>

<script lang='ts' setup>
import { defineProps, getCurrentInstance, onBeforeMount, ref } from 'vue';
import KeystoreService from '@/services/keystone.service';
import { ElMessageBox } from 'element-plus';

type MenuItem = {
  title: string,
  route?: string,
  icon?: string,
  children?: MenuItem[]
}

const props = defineProps<{
  menus: MenuItem[],
  profile?: boolean
}>();

const keystoreService = new KeystoreService();
const user = ref(keystoreService.user.name);

const activeIndex = ref('');
onBeforeMount(() => {
  let app = getCurrentInstance()?.proxy as Any;
  let url = app.$route.fullPath as string;
  for (let i in props.menus || []) {
    if (props.menus[i].route?.includes(url)) {
      activeIndex.value = '' + i;
      break;
    }
    for (let j in props.menus[i].children || []) {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      if (props.menus[i].children![j].route?.includes(url)) {
        activeIndex.value = i + '-' + j;
        break;
      }
    }
  }
});

const handleSelect = (id: string) => {
  activeIndex.value = id;
};

async function signout () {
  await ElMessageBox.confirm('是否确定退出', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  });
  keystoreService.remove();
  location.href = '/user/signin';
}

</script>

<style lang="postcss">
.top-bar {
  width: 100vw;
  height: 64px;
  overflow: hidden;
  background-color: #FFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-menu {
    flex-grow: 2;
  }
  .profile {
    margin-top: -1px;
    padding: 0 10px;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    border-bottom: solid 1px #e6e6e6;
    i {
      font-size: 20px;
    }
  }
}
</style>
